package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Arrays;

@Service
public class DeviceService extends LogicService<DeviceDao, Device, Long> {
    
    @Autowired
    private GreenhouseDao greenhouseDao;
    
    @Autowired
    private DeviceDao deviceDao;
    
    public DeviceService(@Autowired DeviceDao dao) {
        super(dao);
    }
    
    /**
     * 查询单个设备信息
     */
    public Device getDeviceInfo(Long id) throws Exception {
        return dao.findById(id)
                .orElseThrow(() -> new Exception("设备不存在"));
    }
    
    /**
     * 更新设备信息
     * 只更新非null字段，保留原有值
     */
    public Device updateDevice(Device device) throws Exception {
        // 获取原有设备信息
        Device existingDevice = dao.findById(device.getId())
                .orElseThrow(() -> new Exception("设备不存在"));
        
        // 验证必填字段
        if (device.getName() != null) {
            if (device.getName().trim().isEmpty()) {
                throw new Exception("设备名称不能为空");
            }
            existingDevice.setName(device.getName());
        }
        
        // 更新其他字段（只更新非null值）
        if (device.getSerialNumber() != null) {
            existingDevice.setSerialNumber(device.getSerialNumber());
        }
        if (device.getBoxNo() != null) {
            existingDevice.setBoxNo(device.getBoxNo());
        }
        if (device.getDeviceType() != null) {
            existingDevice.setDeviceType(device.getDeviceType());
        }
        if (device.getUnit() != null) {
            existingDevice.setUnit(device.getUnit());
        }
        if (device.getMonitorUrl() != null) {
            existingDevice.setMonitorUrl(device.getMonitorUrl());
        }
        
        // 保存更新后的设备信息
        return dao.save(existingDevice);
    }

    /**
     * 保存设备信息
     */
    public Device saveDevice(Device device, Long greenhouseId) throws Exception {
        // 验证必填字段
        if (device.getName() == null || device.getName().trim().isEmpty()) {
            throw new Exception("设备名称不能为空");
        }
        
        // 查找并设置大棚
        Greenhouse greenhouse = greenhouseDao.findById(greenhouseId)
                .orElseThrow(() -> new Exception("大棚不存在"));
        device.setGreenhouse(greenhouse);
        
        return dao.save(device);
    }

    /**
     * 初始化传感器设备
     */
    public void initializeSensors(Long greenhouseId) throws Exception {
        Greenhouse greenhouse = greenhouseDao.findById(greenhouseId)
                .orElseThrow(() -> new Exception("大棚不存在"));

        // 只创建需要的设备列表
        List<Device> devices = Arrays.asList(
            // NPK传感器
            createDevice("327061330932536077", "土壤氮含量", "nitrogen", "mg/kg", "300023040071", greenhouse),
            createDevice("327061330932536078", "土壤磷含量", "phosphorus", "mg/kg", "300023040071", greenhouse),
            createDevice("327061330932536079", "土壤钾含量", "potassium", "mg/kg", "300023040071", greenhouse),
            
            // 温湿度传感器
            createDevice("327061330933584659", "空气温度", "temperature", "℃", "300023040071", greenhouse),
            createDevice("327061330933584658", "空气相对湿度", "humidity", "%RH", "300023040071", greenhouse)
        );

        // 保存所有设备
        for (Device device : devices) {
            // 检查设备是否已存在
            if (!deviceDao.findBySerialNumber(device.getSerialNumber()).isPresent()) {
                deviceDao.save(device);
            }
        }
    }

    private Device createDevice(String serialNumber, String name, String deviceType, 
                              String unit, String boxNo, Greenhouse greenhouse) {
        Device device = new Device();
        device.setSerialNumber(serialNumber);
        device.setName(name);
        device.setDeviceType(deviceType);
        device.setUnit(unit);
        device.setBoxNo(boxNo);
        device.setGreenhouse(greenhouse);
        return device;
    }
} 